package com.wutuo.tag.provider.service;

import cn.apestar.core.base.BaseService;
import cn.apestar.core.base.GenericMapper;
import cn.apestar.util.CommonUtil;
import com.wutuo.tag.api.TagAPIService;
import com.wutuo.tag.api.request.TagRequest;
import com.wutuo.tag.api.response.TagResponse;
import com.wutuo.tag.provider.dao.TagMapper;
import com.wutuo.tag.provider.domain.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 标签 <br>
 * 类详细说明.
 * <p>
 * Copyright: Copyright (c) 2016年1月26日 下午10:23:33
 * <p>
 *
 * @author lvh
 * @version 1.0.0
 */
@Service public class TagService extends BaseService<Tag, Long> implements TagAPIService {

    private Logger logger = LoggerFactory.getLogger(TagService.class);

    @Autowired private TagMapper tagMapper;

    @Override protected GenericMapper<Tag, Long> getMapper() {

        // TODO Auto-generated method stub
        return tagMapper;
    }

    public void addorUpdate(TagRequest record) {

        if (record.getId() == null) {
            super.add(record);
        } else
            super.update(record);
    }

    public void del(Long id) {

        TagRequest record = new TagRequest();
        record.setId(id);
        record.setDelFlag(false);
        super.delete(record);
    }

    public List<TagResponse> list(TagRequest request) {

        request.setDelFlag(true);
        return tagMapper.list(request);
    }

    public List<TagResponse> listByUserId(TagRequest request) {

        request.setDelFlag(true);
        return tagMapper.listByUserId(request);
    }

    /**
     * 翻译TAG
     *
     * @param model
     * @param tKey
     * @param skey
     * @return
     */
    public <T> List getTagByTagIds(List<T> model, String tKey, String skey) {

        List<TagResponse> listTag = list(new TagRequest());
        Map map = CommonUtil.listToObject(listTag, "id");
        for (int i = 0; i < model.size(); i++) {
            Object modelS = model.get(i);
            Object o = CommonUtil.getProperty(modelS, tKey);
            if (o == null) {
                continue;
            }

            String id = o.toString();
            String[] ids = id.split(",");
            List<T> s = new ArrayList();
            for (int j = 0; j < ids.length; j++) {
                if (map.containsKey(ids[j])) {
                    Object p = map.get(ids[j]);
                    if (!s.contains(p))
                        s.add((T) p);
                }
            }
            CommonUtil.setProperty(modelS, skey, s);
        }
        return model;
    }

}
